package net.arogarth.aws.android.lib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

import net.arogarth.aws.android.lib.ext.SignedRequestsHelper;

public class AmazonAWS {
//	private String region = "";
	protected String URL = "amazonaws.com";
	protected String awsAccessKey = "";
	protected String awsSecretKey = "";
	public String service = "";
	protected String version = "";

	protected String path = "/";
	
	public AmazonAWS() {
		awsAccessKey = AwsSettings.getAccessKey();
		awsSecretKey = AwsSettings.getSecretKey();
	}
	
	public final Map<String, String> params = new HashMap<String, String>();

	private String getUrl() {
		String url = "";
		url += this.service + ".";
//		if (this.region != "")
//			url += this.region + ".";
		url += this.URL;
		return url;
	}

	protected Element execute() throws AwsRequestException {
		Element root = null;

		SignedRequestsHelper srh;
		try {
			srh = SignedRequestsHelper.getInstance(this.getUrl(),
					this.awsAccessKey, this.awsSecretKey);
			
			if(!this.version.equals(""))
				params.put("Version", this.version);
			
			String sign = srh.sign(params);

			Log.d("REQUEST", sign);
			Log.d("REQUEST", sign.replace("&", "\n").replace("?", "\n"));
			

			HttpClient hc = new DefaultHttpClient();
			HttpGet hg = new HttpGet(sign);
			hg.addHeader("X-Amzn-Authorization", sign);

			HttpResponse response = hc.execute(hg);

			InputStream in = response.getEntity().getContent();

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			
			StringBuilder sb = new StringBuilder();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				Log.d("RESPONSE", line);
				sb.append(line);
			}
			in.close();
			
			StringReader reader = new StringReader( sb.toString() );
			Document dom = builder.parse( new InputSource( reader ) );

			root = dom.getDocumentElement();

			NodeList errors = root.getElementsByTagName("Error");

			for (int i = 0; i < errors.getLength(); ) {
				NodeList error = errors.item(i).getChildNodes();
				String code = "";
				String message = "";

				for (int j = 0; j < error.getLength(); j++) {
					Node n = error.item(j);
					if (n.getNodeName().equalsIgnoreCase("code"))
						code = n.getFirstChild().getNodeValue();
					else if (n.getNodeName().equalsIgnoreCase("message"))
						message = n.getFirstChild().getNodeValue();
				}
				throw new AwsRequestException(code, message);
			}
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		return root;
	}
}
